package com.sky.aspect;


import com.sky.anotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面类，用于切入公共的代码
 */
@Aspect
@Component
@Slf4j
public class AutoFIllAspect {

    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anotation.AutoFill)")
    public void pointCut(){}



    @Before("pointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        //根据不同的操作方法注入不同的依赖
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获取方法上的注解.参数对象，注入的值
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        //根据连接点获取匹配上的方法参数对象
        Object[] objects = joinPoint.getArgs();
        Object object = objects[0];
        if (objects.length==0){
            return;
        }
        //注入的值
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //参数对象的Class对象
        Class<?> aClass = object.getClass();
        //根据不同的操作方法插入不同的依赖
        if (value==OperationType.INSERT){
            Method classDeclaredMethod1 = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method classDeclaredMethod2 = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            Method classDeclaredMethod3 = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method classDeclaredMethod4 = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            classDeclaredMethod1.invoke(object,now);
            classDeclaredMethod2.invoke(object,currentId);
            classDeclaredMethod3.invoke(object,now);
            classDeclaredMethod4.invoke(object,currentId);
        }
        else if (value==OperationType.UPDATE){
            Method classDeclaredMethod2 = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            Method classDeclaredMethod3 = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            classDeclaredMethod2.invoke(object,currentId);
            classDeclaredMethod3.invoke(object,now);
        }
    }

}
/**
 * 新用户注册小程序，
 */
